package com.hua.Thread.designparner;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author: _hua
 * @created: 2019/4/8.
 * @updater:
 * @description:
 */
public class Worker implements Runnable {

    //1.装任务
    private ConcurrentLinkedQueue<Task> taskQueue = new ConcurrentLinkedQueue<Task>();

    //3.装结果
    private ConcurrentHashMap<String,Integer> resultMap = new ConcurrentHashMap<String, Integer>();


    public Worker() {
    }

    @Override
    public void run() {
        while (true){
            Task task = taskQueue.peek();
            if(task == null) break;
            //处理任务，可把这个方法变成抽象方法，具体的业务，继承Worker来实现
            Integer output = handle(task);
            //把处理结果放到Master的结果处理集里面
            this.resultMap.put(task.getId(), output);
        }

    }

    public Integer handle(Task task){
        Integer output = null;
        try {
            //处理任务的耗时。。 比如说进行操作数据库。。。
            Thread.sleep(500);
            output = task.getPrice();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return output;
    }

    public ConcurrentLinkedQueue<Task> getTaskQueue() {
        return taskQueue;
    }

    public void setTaskQueue(ConcurrentLinkedQueue<Task> taskQueue) {
        this.taskQueue = taskQueue;
    }

    public ConcurrentHashMap<String, Integer> getResultMap() {
        return resultMap;
    }

    public void setResultMap(ConcurrentHashMap<String, Integer> resultMap) {
        this.resultMap = resultMap;
    }
}
